$NG.AllReady(function (page, { useAction, useValuesChange, useUpdateRows, useBeforeClick, useDataIndexChange, useClick }) {
    const mstform = $NG.getCmpApi("p_form_svc_cost_budget_chg");
    const dgrid1 = $NG.getCmpApi("p_form_svc_labor_budget_chg");
    const dgrid2 = $NG.getCmpApi("p_form_svc_daliy_budget_chg");
  
    function hiddenInput(table, tabled) {
      //来源主键 || 主键
  
  
      tabled.forEach((item) => {
        $NG.updateUI((updater) => {
          updater.editGrid[item].u_phid.setProps({
            hidden: true,
          });
        });
      });
    }
    // 设置默认值人民币和汇率
    if (page.oType == "add") {
      $NG.updateState((updater) => {
        updater.data.p_form_svc_cost_budget_chg.setProps({
          phid_fcur: {
            label: "人民币",
            value: 1,
          },
          exchangerate: 1,
        });
      });
    }
    useBeforeClick(({ args }) => {
      const isLock = (data) => {
        return data.reduce((value, item) => {
          if (item.checked && item.u_source_phid) {
            value = false;
          }
          return value;
        }, true);
      };
      console.log(`删除行参数`, args);
      let lock = true;
      switch (args[0].containerId) {
        case "p_form_svc_labor_budget_chg":
          const arr1 = dgrid1.getData();
          lock = isLock(arr1);
          break;
        case "p_form_svc_daliy_budget_chg":
          const arr2 = dgrid2.getData();
          lock = isLock(arr2);
          break;
      }
      if (!lock) {
        $NG.alert("不能删除已存在关联记录的数据，只能删除当前表单新增数据！");
      }
      return lock;
    }, "deleterow");
    hiddenInput("p_form_svc_cost_budget_chg", ["p_form_svc_labor_budget_chg", "p_form_svc_daliy_budget_chg"]);
    //toolbar
    var dgrid1_toolbar = $NG.getCmpApi("toolbar_p_form_svc_labor_budget_chg");
    var dgrid2_toolbar = $NG.getCmpApi("toolbar_p_form_svc_daliy_budget_chg");
    const toolbars = [
      // { toolbar: $NG.getCmpApi("toolbar"), items: ["copy", "attachment", "check", "history", "applycheck"] },
      // { toolbar: $NG.getCmpApi("toolbar_top"), items: ["imp", "imp_push", "check", "history", "applycheck"] },
      { toolbar: dgrid1_toolbar, items: ["deleterow", "attachment"] },
      { toolbar: dgrid2_toolbar, items: ["deleterow", "attachment"] },
    ];
    toolbars.forEach(({ toolbar, items }) => {
      return;
      if (toolbar) {
        items
          .map((item) => toolbar.getItem(item)) // 提前获取所有按钮
          .filter(Boolean) // 过滤掉不存在的按钮
          .forEach((toolbarItem) => toolbarItem.setHidden()); // 隐藏按钮
      }
    });
  
    //生成phid
    function generate15DigitNumber(arr) {
      arr.forEach((item) => {
        let str = "";
        // 获取当前时间戳
        let timestamp = Date.now().toString();
        // 如果时间戳不足 15 位，计算需要补充的位数
        let remainingLength = 15 - timestamp.length;
        if (remainingLength > 0) {
          // 生成指定长度的随机数
          let randomPart = "";
          for (let i = 0; i < remainingLength; i++) {
            randomPart += Math.floor(Math.random() * 10);
          }
          // 将时间戳和随机数拼接成 15 位数字
          str = String(timestamp + randomPart);
        } else {
          // 如果时间戳长度超过 15 位，截取前 15 位
          str = String(timestamp.slice(0, 15));
        }
        console.log(str);
        if (!item.u_phid) {
          item.u_phid = str;
          dgrid1.refreshView();
          dgrid2.refreshView();
        }
      });
    }
    let lockTime = 0;
    let saveLock = true;
    if (page.oType == "add" || page.oType == "edit") {
      lockTime = setInterval(() => {
        console.log(`检测中~~~`);
        if (mstform.getItem("u_source_phid").getValue()) {
          $NG.execServer("getSvcIsimport", { source: mstform.getItem("u_source_phid").getValue() }, (res) => {
            console.log(`引用结果`, res);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (_data.app_status == "1") {
              return;
            }
            saveLock = false;
            $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
          });
          clearInterval(lockTime);
        }
      }, 1000);
    }
    //计算服务费率
    function serviceLv() {
      return;
      $NG.updateState((updater) => {
        updater.data.p_form_svc_cost_budget_chg.setProps({
          u_svc_rate: ((Number(mstform.getItem("u_total_svc_amt").getValue()) || 0) / (Number(mstform.getItem("u_cnt_amt_vat").getValue()) || 0)).toFixed(4),
        });
      });
    }
    useBeforeClick(({ args }) => {
      try {
        if (!saveLock) {
          $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
          return false;
        }
        return true;
      } catch (err) {
        console.log(`err`, err);
      }
    }, "save");
    useBeforeClick(({ args }) => {
      if (!saveLock) {
        $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
        return false;
      }
      return true;
    }, "check");
    dgrid1_toolbar.insert({
      id: "dgrid1ShowUI",
      text: "显示原预算数据",
      iconCls: "icon-New",
    });
    dgrid1_toolbar.insert({
      id: "dgrid1hideUI",
      text: "隐藏原预算数据",
      iconCls: "icon-New",
    });
  
    dgrid2_toolbar.insert({
      id: "dgrid2ShowUI",
      text: "显示原预算数据",
      iconCls: "icon-New",
    });
    dgrid2_toolbar.insert({
      id: "dgrid2hideUI",
      text: "隐藏原预算数据",
      iconCls: "icon-New",
    });
    useClick(() => {
      dgrid1ShowUI();
    }, "dgrid1ShowUI");
    useClick(() => {
      dgrid1hideUI();
    }, "dgrid1hideUI");
  
    useClick(() => {
      dgrid2ShowUI();
    }, "dgrid2ShowUI");
    useClick(() => {
      dgrid2hideUI();
    }, "dgrid2hideUI");
  
    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    if (mstform) {
      cntMFilter();
      if (mstform.getItem("phid_pc").getValue()) {
        getPtInfoByPhid();
        getCntCount("p_form_svc_cost_budget_chg", "u_cnt", CntEvent);
      }
      if (page.oType == "add") {
        mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() || "" + "服务费用预算单变更单");
        useValuesChange(({ args }) => {
          mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() + "服务费用预算单变更单");
          cntMFilter();
        }, "p_form_svc_cost_budget_chg.phid_pc");
      }
      useValuesChange(({ args }) => {
        getPtInfoByPhid();
        cntMFilter();
        $NG.updateState((updater) => {
          updater.data.p_form_svc_cost_budget_chg.setProps({
            u_pc_no: args[0].phid_pc.PhId,
            u_cnt: {
              label: null,
              value: null,
            },
          });
          setTimeout(() => {
            cntMFilter();
          }, 200);
        });
        getCntCount("p_form_svc_cost_budget_chg", "u_cnt", CntEvent);
        getSvcTotalAmt()
        getSbqdHeadInfoByPhidPc()
      }, "p_form_svc_cost_budget_chg.phid_pc");
  
      useValuesChange(({ args }) => {
        // 添加明细行
        CntEvent();
      }, "p_form_svc_cost_budget_chg.u_cnt");
    }
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
  
  
    useDataIndexChange(({ args, instance }) => {
      var items = args[0];
      if (items.u_position) {
        $NG.execServer("getSimpleDataByPhid", { phid: items.u_position }, function (res) {
          if (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // 尝试将 c_descript 转换为数字
            const personnelRate = Number(datas.c_descript);
            if (isNaN(personnelRate)) {
              // 如果转换失败，可以设置一个默认值或者处理错误
              console.error("Invalid value for u_personnel_rate:", datas.c_descript);
            }
            items.u_personnel_rate = personnelRate;
            caculatedgrid();
          }
          dgrid1.refreshView();
        });
      }
      instance.updateRow(items);
    }, "p_form_svc_labor_budget_chg.u_position");
    useUpdateRows(({ args }) => {
      caculatedgrid();
      serviceLv();
      generate15DigitNumber(args[0]);
      reduceNum();
    }, "p_form_svc_labor_budget_chg");
  
    useUpdateRows(({ args }) => {
      const rows = args[0];
      console.log(`调试服务`, args[0]);
      args[0].forEach((item) => {
        let count = 0;
        for (let i = 1; i <= 12; i++) {
          let key = "u_expenses_" + String(i).padStart(2, "0");
          count += Number(item[key]) || 0;
        }
        item.u_annual_svc_amt = count;
      });
  
      caculatedgrid();
      //默认年度
      let bpbj_amt = args[0].reduce((value, item) => {
        item.u_year = String(new Date().getFullYear());
        item.u_year_EXName = String(new Date().getFullYear());
        if (item.u_expense_code == 8570000000000393) {
          value += Number(item.u_amt) || 0;
        }
      }, 0);
      $NG.updateState((updater) => {
        updater.data.p_form_svc_cost_budget_chg.setProps({
          u_srv_spare_parts: bpbj_amt,
        });
      });
  
      reduceNum();
      dgrid1.refreshView();
    }, "p_form_svc_daliy_budget_chg");
  
    useUpdateRows(({ args }) => {
      caculatedgrid();
      serviceLv();
      generate15DigitNumber(args[0]);
      reduceNum();
    }, "p_form_svc_daliy_budget_chg");
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
  
  
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
  
    //计算表头数据差额
    function reduceNum() {
      setTimeout(() => {
        const ffrg = mstform.getItem("u_total_svc_labor_amt").getValue() - mstform.getItem("u_total_svc_labor_amt_ori").getValue();
        const rcfy = mstform.getItem("u_total_daily_amt").getValue() - mstform.getItem("u_total_daily_amt_ori").getValue();
        const fwtotal = mstform.getItem("u_total_svc_amt").getValue() - mstform.getItem("u_total_svc_amt_ori").getValue();
        const fwrate = mstform.getItem("u_svc_rate").getValue() - mstform.getItem("u_svc_rate_ori").getValue();
        const sub = mstform.getItem("u_srv_sub").getValue() - mstform.getItem("u_srv_sub_ori").getValue();
        const bpbj = mstform.getItem("u_srv_spare_parts").getValue() - mstform.getItem("u_srv_spare_parts_ori").getValue();
        $NG.updateState((updater) => {
          updater.data.p_form_svc_cost_budget_chg.setProps({
            u_total_svc_labor_amt_gap: ffrg,
            u_total_daily_amt_gap: rcfy,
            u_total_svc_amt_gap: fwtotal,
            u_svc_rate_gap: fwrate,
            u_srv_sub_gap: sub,
            u_srv_spare_parts_gap: bpbj,
            u_svc_rate: ((Number(mstform.getItem("u_cnt_amt").getValue()) || 0)) && ((Number(mstform.getItem("u_total_svc_amt").getValue()) || 0) / (Number(mstform.getItem("u_cnt_amt").getValue()) || 0)).toFixed(4),
          });
        });
      }, 300);
    }
  
    function CntEvent() {
      if (page.oType == "add") {
        getCntInfo();
        if (dgrid1.getData().length != 0) {
          dgrid1.clearRows();
        }
        if (dgrid1.getData().length != 0) {
          dgrid2.clearRows();
        }
  
        setTimeout(() => {
          // 赋值
          function _sum(num) {
            $NG.updateState((updater) => {
              updater.data.p_form_svc_cost_budget_chg.setProps({
                u_total_svc_amt_ori: num,
              });
            });
          }
          // 临时存储上一次的费用
          const _countMaps = {
            _d1: 0,
            _d2: 0,
            _d3: 0,
            set d1(value) {
              this._d1 = value;
              _sum(this._d1 + this._d2 + this._d3);
            },
            set d2(value) {
              this._d2 = value;
              _sum(this._d1 + this._d2 + this._d3);
            },
            set d3(value) {
              this._d3 = value;
              _sum(this._d1 + this._d2 + this._d3);
            },
          };
          Object.defineProperties(_countMaps, {
            _d1: {
              configurable: false,
              writable: true,
              enumerable: false,
              value: 0,
            },
            _d2: {
              configurable: false,
              writable: true,
              enumerable: false,
              value: 0,
            },
            _d3: {
              configurable: false,
              writable: true,
              enumerable: false,
              value: 0,
            },
          });
          if (dgrid1) {
            $NG.execServer("getSvcLaborBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
              let _data = null;
              if (typeof res.data === "string") {
                _data = JSON.parse(res.data);
              } else {
                _data = res.data;
              }
              console.log(`测试测试`, _data, res);
              //默认增行,批量新增表体数据
              var gridArr = []; //定义表体数组
              var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
              for (var i = 0; i < gridCount; i++) {
                var gridObj = {};
                const reat = _data[i].extendObjects.u_svc_rate;
                const phid = _data[i].extendObjects.mphid;
                if (!mstform.getItem("u_svc_rate").getValue()) {
                  $NG.updateState((updater) => {
                    updater.data.p_form_svc_cost_budget_chg.setProps({
                      u_svc_rate_ori: reat,
                      u_svc_rate: reat,
                      u_source_phid: phid,
                    });
                  });
                }
                //对表体字段进行赋值,可以取数据库中的值进行赋值
  
                // 年度
                gridObj.u_year = _data[i].extendObjects.u_year;
                // 人员岗位
                gridObj.u_position_EXName = _data[i].extendObjects.position_name;
                gridObj.u_position = _data[i].extendObjects.position_phid;
                // 人员费率
                gridObj.u_personnel_rate = _data[i].extendObjects.u_personnel_rate;
                // 人工费合计
                gridObj.u_svc_labor_amt_ori = _data[i].extendObjects.u_amt;
                gridObj.u_svc_labor_amt = _data[i].extendObjects.u_amt;
                // 数量
                gridObj.u_qty = _data[i].extendObjects.u_qty;
                gridObj.u_qty_ori = _data[i].extendObjects.u_qty;
                gridObj.u_source_phid = _data[i].extendObjects.phid;
                gridObj.u_man_months = _data[i].extendObjects.u_man_months;
                gridObj.u_man_months_ori = _data[i].extendObjects.u_man_months;
  
                // 1- 12 月
                for (let j = 1; j <= 12; j++) {
                  const _str = `u_man_days_${j < 10 ? "0" + j : j}`;
                  const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
                  gridObj[_str] = _data[i].extendObjects[_str];
                  gridObj[_str_ori] = _data[i].extendObjects[_str];
                }
                gridArr.push(gridObj);
              }
              //调用新增表体行数据的函数
              let _count = 0;
              gridArr.forEach((item) => {
                _count += item.u_svc_labor_amt_ori;
              });
              $NG.updateState((updater) => {
                _countMaps.d1 = _count;
                updater.data.p_form_svc_cost_budget_chg.setProps({
                  u_total_svc_labor_amt_ori: _count,
                });
              });
              dgrid1.addRows(gridArr);
            });
          }
          if (dgrid2) {
            $NG.execServer("getSvcDaliyBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
              let _data = [];
              if (typeof res.data === "string") {
                _data = JSON.parse(res.data);
              } else {
                _data = res.data;
              }
              // console.log(`测试测试日常`, _data);
              //默认增行,批量新增表体数据
              let gridArr = []; //定义表体数组
              let gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
              for (let i = 0; i < gridCount; i++) {
                let extendObj = _data[i].extendObjects; // 缓存extendObjects，避免重复访问
                // 对表体字段进行赋值
                let gridObj = {
                  u_year: extendObj.u_year || "",
                  u_annual_svc_amt: extendObj.u_annual_svc_amt || 0,
                  u_annual_svc_amt_ori: extendObj.u_annual_svc_amt || 0,
                  u_expense_code: extendObj.u_expense_code || "",
                  u_expense_code_EXName: extendObj.u_expense_name || "",
                  u_expense_description: extendObj.u_expense_description || "",
                  u_source_phid: extendObj.phid || "",
                };
                // 1- 12 月
                for (let j = 1; j <= 12; j++) {
                  const monthStr = j < 10 ? `0${j}` : `${j}`;
                  gridObj[`u_expenses_${monthStr}`] = extendObj[`u_expenses_${monthStr}`] || 0;
                  gridObj[`u_expenses_${monthStr}_ori`] = extendObj[`u_expenses_${monthStr}`] || 0;
                }
                console.log(`测试测试日常`, gridObj);
                gridArr.push(gridObj);
              }
              let _count = 0;
              gridArr.forEach((item) => {
                _count += item.u_annual_svc_amt;
              });
              $NG.updateState((updater) => {
                _countMaps.d2 = _count;
                updater.data.p_form_svc_cost_budget_chg.setProps({
                  u_total_daily_amt_ori: _count,
                });
              });
              // console.log(`调试`, gridArr);
              //调用新增表体行数据的函数
              dgrid2.addRows(gridArr);
              dgrid2.refreshView();
            });
          }
        }, 200);
      }
    }
  
    // 返回当月最大天数
    function getDaysInMonth(year, month) {
      const y = parseInt(year, 10);
      const m = parseInt(month, 10);
      return new Date(y, m, 0).getDate();
    }
    function caculatedgrid() {
      let u_svc_labor_amt = 0; //服务人工费
      let u_total_daily_amt = 0; //合计日常费用
      let u_total_svc_amt = 0; //合计总费用
      let BeiJian = 0; //服务备件 8570000000000393 保修材料耗用
      let FenBao = 0; //服务分包 8570000000000394 产品维修
      let BeiJian_ori = 0; //服务备件 8570000000000393 保修材料耗用
      let FenBao_ori = 0; //服务分包 8570000000000394 产品维修
      const Rows1 = $NG.getCmpApi("p_form_svc_labor_budget_chg").getData(); //服务人工页签
      const Rows2 = $NG.getCmpApi("p_form_svc_daliy_budget_chg").getData(); //日常费用页签
      dgrid1.getData().forEach((items, rowIndex) => {
        let total = 0;
        for (let i = 1; i <= 12; i++) {
          let maxDay = getDaysInMonth(items.u_year, i);
          const key = "u_man_days_" + String(i).padStart(2, "0");
          const manDays = Number(items[key]);
          if (isNaN(manDays)) {
            items[key] = 0;
          } else if (manDays > maxDay) {
            items[key] = 0;
            $NG.alert(`第${rowIndex + 1}行第${i}月人天不能超过${maxDay}天`);
          }
          total += Number(items[key] > 21.75 ? 21.75 : items[key]) || 0;
        }
        // 人月=人天/21.75
        // 人工费合计=人员费率*数量*人月
        items.u_man_months = total / 21.75;
        items.u_svc_labor_amt = ((Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_man_months) || 0)).toFixed(2);
        u_svc_labor_amt += Number(items.u_svc_labor_amt) || 0;
        if (!items.u_year) {
          items.u_year = new Date().getFullYear();
          items.u_year_EXName = new Date().getFullYear();
        }
        dgrid1.refreshView();
      });
      dgrid2.getData().forEach((items) => {
        let count = 0;
        if (items.u_expense_code == 8570000000000393) {
          BeiJian += Number(items.u_annual_svc_amt) || 0;
          BeiJian_ori += Number(items.u_annual_svc_amt_ori) || 0;
        }
        if (items.u_expense_code == 8570000000000394) {
          FenBao += Number(items.u_annual_svc_amt) || 0;
          FenBao_ori += Number(items.u_annual_svc_amt_ori) || 0;
        }
  
        for (let i = 1; i <= 12; i++) {
          let key = "u_expenses_" + String(i).padStart(2, "0");
          count += Number(items[key]) || 0;
        }
        items.u_annual_svc_amt = count;
        u_total_daily_amt += Number(items.u_annual_svc_amt) || 0;
        dgrid1.refreshView();
      });
      //   u_total_svc_amt = u_total_svc_labor_amt + u_total_daily_amt;
      u_total_svc_amt = u_svc_labor_amt + u_total_daily_amt;
  
      // console.log(`测试测试`, u_svc_labor_amt, u_total_daily_amt, u_total_svc_amt);

      const totalori = mstform.getItem("u_total_svc_amt_ori").getValue()
      const rgori = mstform.getItem("u_total_svc_labor_amt_ori").getValue()
      const rcori = mstform.getItem("u_total_daily_amt_ori").getValue()
      const fbori = FenBao_ori
      const bjori = BeiJian_ori
      const rateori = mstform.getItem("u_svc_rate_ori").getValue()

      const u_svc_rate = mstform.getItem("u_svc_rate").getValue()

      let u_gross_profit_rate = (Number(window._catch_sbqd_amt.cnt_amt) || 0) && ((Number(window._catch_sbqd_amt.cnt_amt) || 0) - ((Number(window._catch_sbqd_amt.project_amt) || 0) + (Number(u_total_svc_amt) || 0))) / (Number(window._catch_sbqd_amt.cnt_amt) || 0)
      $NG.updateState((updater) => {
        updater.data.p_form_svc_cost_budget_chg.setProps({
          u_total_svc_labor_amt: u_svc_labor_amt, //
          u_total_daily_amt: u_total_daily_amt, //
          u_total_svc_amt: u_total_svc_amt, //
          u_srv_spare_parts: BeiJian,
          u_srv_spare_parts_ori: BeiJian_ori,
          u_srv_sub: FenBao,
          u_srv_sub_ori: FenBao_ori,
          u_gross_profit_rate: u_gross_profit_rate,

          u_total_svc_amt_gap: u_total_svc_amt - totalori,
          u_total_svc_labor_amt_gap:u_svc_labor_amt - rgori,
          u_total_daily_amt_gap: u_total_daily_amt - rcori,
          u_srv_sub_gap: FenBao - fbori,
          u_srv_spare_parts_gap: BeiJian - bjori, 
          u_svc_rate_gap:u_svc_rate - rateori,
          

          u_total_svc_amt_gap_sum: (Number(window._catch_svc_total_amt.total_amt) || 0) + u_total_svc_amt - totalori,
          u_svc_labor_amt_gap_sum: (Number(window._catch_svc_total_amt.rg_total_amt) || 0) + u_svc_labor_amt - rgori,
          u_total_daily_amt_gap_sum: (Number(window._catch_svc_total_amt.rc_total_amt) || 0) + u_total_daily_amt - rcori,
          u_srv_sub_gap_sum: (Number(window._catch_svc_total_amt.fb_total_amt) || 0) + FenBao - fbori,
          u_srv_spare_parts_gap_sum: (Number(window._catch_svc_total_amt.bj_total_amt) || 0) + BeiJian - bjori,
          u_svc_rate_gap_sum: (Number(window._catch_svc_total_amt.fl_total_amt) || 0) + u_svc_rate - rateori,
          u_gross_profit_rate_gap:u_gross_profit_rate - window._catch_sbqd_amt.total_rate
        });
      });
    }
    cntMFilter();
    function cntMFilter() {
      if (!mstform.getItem("phid_pc").getValue()) {
        return;
      }
      $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_svc_cost_budget_chg.u_cnt.setProps({
          onBeforeOpen: async () => {
            var phid_pc = $NG.getCmpApi("p_form_svc_cost_budget_chg").getItem("phid_pc").getValue();
            if (!phid_pc) {
              $NG.alert("请先选择项目");
              return false;
            } else {
              return true;
            }
          },
          ...(!!$NG.getCmpApi("p_form_svc_cost_budget_chg").getItem("phid_pc").getValue() && {
            clientSqlFilter: {
              bill_type: 1,
              phid_pc: $NG.getCmpApi("p_form_svc_cost_budget_chg").getItem("phid_pc").getValue(),
            },
          }),
        });
      });
    }
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log(datas);
          $NG.updateState((updater) => {
            updater.data.p_form_svc_cost_budget_chg.setProps({
              u_agreed_sts_dt: datas.start_date, //计划完工日期
              u_agreed_pcl_dt: datas.end_date, //计划竣工日期
              u_pc_no: datas.pc_no, //项目编码
              //项目类型
              u_pc_type: {
                label: datas.type_name,
                value: datas.type_phid,
              },
              u_sqgw: {
                //售前顾问
                value: datas.user_sqgw_phid,
                label: datas.user_sqgw_name,
              },
              u_division: {
                //事业部
                value: datas.division_phid,
                label: datas.division_name,
              },
              u_regional_center: {
                //区域中心
                value: datas.regional_center_phid,
                label: datas.regional_center_name,
              },
              u_product_line: {
                //产品线
                value: datas.midwife_phid,
                label: datas.midwife_name,
              },
            });
          });
          // 判断是否是提前施工
        let tqLock = true;
        if(datas.user_sf_tqsg == '1'){
            tqLock = false
        } else {
            tqLock = true
        }
        console.log(`是否提前施工项目`,datas.user_sf_tqsg);
        $NG.updateUI((updater)=>{
                updater.fieldSetForm.p_form_svc_cost_budget_chg.u_cnt.setProps({
                    required:tqLock
                })
            })
        });
      }
    }
    function getCntInfo() {
      $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(`合同：`, datas);
        //帮助字段赋值
        $NG.updateState((updater) => {
          updater.data.p_form_svc_cost_budget_chg.setProps({
            //   u_agreed_sts_dt: datas.start_dt, //计划完工日期
            //   u_agreed_pcl_dt: datas.end_dt, //计划竣工日期
            u_cnt_no: datas.pcm_no,
            u_cnt_amt_vat: datas.cnt_sum_vat_fc,
            u_warrant_period: datas.user_htbzq,
          });
        });
      });
    }
    //function dgrid1
    function dgrid1ShowUI(params) {
      $NG.updateUI((updater) => {
        for (let j = 1; j <= 12; j++) {
          const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
          updater.editGrid.p_form_svc_labor_budget_chg[_str_ori].setProps({
            hidden: false, //隐藏
          });
        }
        const fields = ["u_qty_ori", "u_svc_labor_amt_ori", "u_man_months_ori"];
        fields.forEach((field) => {
          updater.editGrid.p_form_svc_labor_budget_chg[field].setProps({
            hidden: false, //隐藏
          });
        });
      });
    }
    function dgrid1hideUI(params) {
      $NG.updateUI((updater) => {
        for (let j = 1; j <= 12; j++) {
          const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
          updater.editGrid.p_form_svc_labor_budget_chg[_str_ori].setProps({
            hidden: true, //隐藏
          });
        }
        const fields = ["u_qty_ori", "u_svc_labor_amt_ori", "u_man_months_ori"];
        fields.forEach((field) => {
          updater.editGrid.p_form_svc_labor_budget_chg[field].setProps({
            hidden: true, //隐藏
          });
        });
      });
    }
    //function dgrid2
    function dgrid2ShowUI(params) {
      $NG.updateUI((updater) => {
        for (let j = 1; j <= 12; j++) {
          const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
          updater.editGrid.p_form_svc_daliy_budget_chg[_str_ori].setProps({
            hidden: false, //隐藏
          });
        }
        const fields = ["u_annual_svc_amt_ori"];
        fields.forEach((field) => {
          updater.editGrid.p_form_svc_daliy_budget_chg[field].setProps({
            hidden: false, //隐藏
          });
        });
      });
    }
    function dgrid2hideUI(params) {
      $NG.updateUI((updater) => {
        for (let j = 1; j <= 12; j++) {
          const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
          updater.editGrid.p_form_svc_daliy_budget_chg[_str_ori].setProps({
            hidden: true, //隐藏
          });
        }
        const fields = ["u_annual_svc_amt_ori"];
        fields.forEach((field) => {
          updater.editGrid.p_form_svc_daliy_budget_chg[field].setProps({
            hidden: true, //隐藏
          });
        });
      });
    }
  
    //////////////////////////////////////插入按钮 ////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮 ////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮 ////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮 ////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮 ////////////////////////////////////////////////////////
  
    if (page.oType == "add" || page.oType == "edit") {
      {
        //添加按钮
        $NG.getCmpApi("toolbar_p_form_svc_daliy_budget_chg").insert({
          id: "fyadd",
          text: "选择费用项目",
          iconCls: "icon-New",
        });
      }
    }
    useClick(async function ({ args }) {
      // 打开帮助选择器并应用过滤条件
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "cost_pc_fw",
          valueField: "d.phid.",
          labelField: "d.u_name",
          //clientSqlFilter:  // 应用过滤条件
        })
        .then((data) => {
          console.log(data);
  
          let gridArr = []; // 初始化 gridArr 数组
          for (var i = 0; i < data.length; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
              u_expense_code: "",
            };
            // 对表体字段进行赋值, 可以取数据库中的值进行赋值
            gridObj.u_expense_code = data[i].origin.phid;
            gridObj.u_expense_code_EXName = data[i].origin.u_name;
            // 关键步骤：将 gridObj 添加到 gridArr 数组中
            gridArr.push(gridObj);
          }
          console.log(gridArr); // 确保这里打印出来的 gridArr 不是空的
          dgrid2.addRows(gridArr); // 将数据添加到表格组件中
        });
    }, "fyadd");
    // 获取服务费用变更累计费用
    getSvcTotalAmt()
    function getSvcTotalAmt(){
        window._catch_svc_total_amt = {}
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if(!phid_pc) return 
        $NG.execServer("getSvcTotalAmt",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)[0].extendObjects
            window._catch_svc_total_amt = {..._data}
        })
    }
    getSbqdHeadInfoByPhidPc()
    function getSbqdHeadInfoByPhidPc(){
        window._catch_sbqd_amt = {}
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if(!phid_pc) return
        $NG.execServer("getSbqdHeadInfoByPhidPc",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)[0].extendObjects
            const map = {
                cnt_amt:_data.u_cnt_amt,
                project_amt: (Number(_data.u_total_cost_amt) || 0) - (Number(_data.u_svc_cost_amt) || 0),
                total_rate:_data.u_signed_gm_rate,
                outher:_data
            }
            window._catch_sbqd_amt = {...map}
            if(page.oType != 'view'){
                $NG.updateState((updater)=>{
                    updater.data.p_form_svc_cost_budget_chg.setProps({
                        u_gross_profit_rate_ori:_data.u_signed_gm_rate  
                    })
                })
            }
        })
    }
  });
  
  //获取合同数量
  function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
      console.log(res, "count");
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              if (fun) {
                fun();
              }
            }, 200);
          });
      }
    });
  }
  